import { get, post, put, del } from '@/utils/request'
import { API_ENDPOINTS, replaceUrlParams } from '@/config/api'

/**
 * 消息管理API
 */

// 获取消息列表
export function getMessagesList(params = {}) {
  return get(API_ENDPOINTS.MESSAGES.LIST, {
    page: params.page || 0,
    size: params.size || 20,
    type: params.type || '',
    status: params.status || '',
    keyword: params.keyword || '',
    startDate: params.startDate || '',
    endDate: params.endDate || ''
  })
}

// 获取消息详情
export function getMessageDetail(messageId) {
  const url = replaceUrlParams(API_ENDPOINTS.MESSAGES.DETAIL, { id: messageId })
  return get(url)
}

// 标记消息为已读
export function markMessageAsRead(messageId) {
  const url = replaceUrlParams(API_ENDPOINTS.MESSAGES.MARK_READ, { id: messageId })
  return post(url)
}

// 批量标记消息为已读
export function markAllMessagesAsRead(messageIds = []) {
  return post(API_ENDPOINTS.MESSAGES.MARK_READ.replace('/{id}', '/batch'), {
    messageIds: messageIds
  })
}

// 删除消息
export function deleteMessage(messageId) {
  const url = replaceUrlParams(API_ENDPOINTS.MESSAGES.DELETE, { id: messageId })
  return del(url)
}

// 批量删除消息
export function deleteMessages(messageIds) {
  return post(API_ENDPOINTS.MESSAGES.DELETE.replace('/{id}', '/batch'), {
    messageIds: messageIds
  })
}

// 发送消息
export function sendMessage(messageData) {
  return post(API_ENDPOINTS.MESSAGES.SEND, {
    type: messageData.type,
    title: messageData.title,
    content: messageData.content,
    targetId: messageData.targetId,
    extra: messageData.extra || {}
  })
}

// 获取消息统计
export function getMessageStatistics() {
  return get(API_ENDPOINTS.MESSAGES.STATISTICS)
}

// 获取未读消息数量
export function getUnreadCount() {
  return get(API_ENDPOINTS.MESSAGES.STATISTICS + '/unread-count')
}

// 消息类型枚举
export const MESSAGE_TYPES = {
  SYSTEM: 'system',
  ORDER: 'order',
  FINANCE: 'finance',
  REVIEW: 'review',
  PROMOTION: 'promotion',
  CUSTOMER: 'customer'
}

// 消息类型文本映射
export const MESSAGE_TYPE_TEXT = {
  [MESSAGE_TYPES.SYSTEM]: '系统通知',
  [MESSAGE_TYPES.ORDER]: '订单消息',
  [MESSAGE_TYPES.FINANCE]: '财务消息',
  [MESSAGE_TYPES.REVIEW]: '评价消息',
  [MESSAGE_TYPES.PROMOTION]: '推广消息',
  [MESSAGE_TYPES.CUSTOMER]: '客户消息'
}

// 消息类型颜色映射
export const MESSAGE_TYPE_COLOR = {
  [MESSAGE_TYPES.SYSTEM]: 'info',
  [MESSAGE_TYPES.ORDER]: 'primary',
  [MESSAGE_TYPES.FINANCE]: 'success',
  [MESSAGE_TYPES.REVIEW]: 'warning',
  [MESSAGE_TYPES.PROMOTION]: 'danger',
  [MESSAGE_TYPES.CUSTOMER]: 'info'
}

// 消息状态枚举
export const MESSAGE_STATUS = {
  UNREAD: 'unread',
  READ: 'read',
  DELETED: 'deleted'
}

// 消息状态文本映射
export const MESSAGE_STATUS_TEXT = {
  [MESSAGE_STATUS.UNREAD]: '未读',
  [MESSAGE_STATUS.READ]: '已读',
  [MESSAGE_STATUS.DELETED]: '已删除'
}

// 消息优先级枚举
export const MESSAGE_PRIORITY = {
  LOW: 'low',
  NORMAL: 'normal',
  HIGH: 'high',
  URGENT: 'urgent'
}

// 消息优先级文本映射
export const MESSAGE_PRIORITY_TEXT = {
  [MESSAGE_PRIORITY.LOW]: '低',
  [MESSAGE_PRIORITY.NORMAL]: '普通',
  [MESSAGE_PRIORITY.HIGH]: '高',
  [MESSAGE_PRIORITY.URGENT]: '紧急'
}

// 消息优先级颜色映射
export const MESSAGE_PRIORITY_COLOR = {
  [MESSAGE_PRIORITY.LOW]: 'info',
  [MESSAGE_PRIORITY.NORMAL]: 'primary',
  [MESSAGE_PRIORITY.HIGH]: 'warning',
  [MESSAGE_PRIORITY.URGENT]: 'danger'
}

// 获取消息类型文本
export function getMessageTypeText(type) {
  return MESSAGE_TYPE_TEXT[type] || '未知类型'
}

// 获取消息类型颜色
export function getMessageTypeColor(type) {
  return MESSAGE_TYPE_COLOR[type] || 'info'
}

// 获取消息状态文本
export function getMessageStatusText(status) {
  return MESSAGE_STATUS_TEXT[status] || '未知状态'
}

// 获取消息优先级文本
export function getMessagePriorityText(priority) {
  return MESSAGE_PRIORITY_TEXT[priority] || '普通'
}

// 获取消息优先级颜色
export function getMessagePriorityColor(priority) {
  return MESSAGE_PRIORITY_COLOR[priority] || 'primary'
}

// 格式化消息时间
export function formatMessageTime(time) {
  if (!time) return ''
  
  const now = new Date()
  const messageTime = new Date(time)
  const diff = now - messageTime
  
  // 小于1分钟
  if (diff < 60 * 1000) {
    return '刚刚'
  }
  
  // 小于1小时
  if (diff < 60 * 60 * 1000) {
    const minutes = Math.floor(diff / (60 * 1000))
    return `${minutes}分钟前`
  }
  
  // 小于1天
  if (diff < 24 * 60 * 60 * 1000) {
    const hours = Math.floor(diff / (60 * 60 * 1000))
    return `${hours}小时前`
  }
  
  // 小于7天
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    const days = Math.floor(diff / (24 * 60 * 60 * 1000))
    return `${days}天前`
  }
  
  // 超过7天显示具体日期
  return messageTime.toLocaleDateString()
}

// 创建消息对象
export function createMessage(data) {
  return {
    id: data.id || Date.now(),
    type: data.type || MESSAGE_TYPES.SYSTEM,
    title: data.title || '',
    content: data.content || '',
    priority: data.priority || MESSAGE_PRIORITY.NORMAL,
    isRead: data.isRead || false,
    createTime: data.createTime || new Date().toISOString(),
    updateTime: data.updateTime || new Date().toISOString(),
    extra: data.extra || {},
    targetId: data.targetId || null,
    senderId: data.senderId || null,
    senderName: data.senderName || '系统'
  }
}

// 验证消息数据
export function validateMessageData(data) {
  const errors = []
  
  if (!data.type || !Object.values(MESSAGE_TYPES).includes(data.type)) {
    errors.push('消息类型无效')
  }
  
  if (!data.title || data.title.trim().length === 0) {
    errors.push('消息标题不能为空')
  }
  
  if (!data.content || data.content.trim().length === 0) {
    errors.push('消息内容不能为空')
  }
  
  if (data.title && data.title.length > 100) {
    errors.push('消息标题不能超过100个字符')
  }
  
  if (data.content && data.content.length > 1000) {
    errors.push('消息内容不能超过1000个字符')
  }
  
  return {
    valid: errors.length === 0,
    errors
  }
}

// 消息模板
export const MESSAGE_TEMPLATES = {
  ORDER_NEW: {
    type: MESSAGE_TYPES.ORDER,
    title: '新订单通知',
    content: '您有一个新的订单，请及时处理。'
  },
  ORDER_TIMEOUT: {
    type: MESSAGE_TYPES.ORDER,
    title: '订单超时提醒',
    content: '订单已超过预定时间，请尽快处理。'
  },
  FINANCE_WITHDRAW: {
    type: MESSAGE_TYPES.FINANCE,
    title: '提现到账通知',
    content: '您的提现申请已处理完成，请注意查收。'
  },
  REVIEW_NEW: {
    type: MESSAGE_TYPES.REVIEW,
    title: '客户评价通知',
    content: '您收到了新的客户评价。'
  },
  SYSTEM_MAINTENANCE: {
    type: MESSAGE_TYPES.SYSTEM,
    title: '系统维护通知',
    content: '系统将进行维护升级，请提前做好准备。'
  }
}

// 获取消息模板
export function getMessageTemplate(templateKey) {
  return MESSAGE_TEMPLATES[templateKey] || null
}

// 应用消息模板
export function applyMessageTemplate(templateKey, data = {}) {
  const template = getMessageTemplate(templateKey)
  if (!template) {
    return null
  }
  
  return createMessage({
    ...template,
    ...data
  })
}
